import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Switch,
  Tabs,
  Row,
  Col,
  Popconfirm,
  Image,
  Typography,
  App,
  Layout
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import productService from '../../services/productService';
import type {
  Product,
  ProductCategory,
  ProductAttribute,
  CreateCategoryParams,
  CreateAttributeParams,
  ProductListParams
} from '../../services/productService';
import './ProductsPage.css';

const { TabPane } = Tabs;
const { Title } = Typography;

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

const ProductsPage: React.FC = () => {
  const { message } = App.useApp();
  const navigate = useNavigate();

  const [activeTab, setActiveTab] = useState('products');

  // 返回首页
  const handleBack = () => {
    navigate('/dashboard');
  };

  // 商品相关状态
  const [products, setProducts] = useState<Product[]>([]);
  const [productLoading, setProductLoading] = useState(false);
  const [productPagination, setProductPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 分类相关状态
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [categoryLoading, setCategoryLoading] = useState(false);
  const [categoryPagination, setCategoryPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<ProductCategory | null>(null);
  const [categoryForm] = Form.useForm();

  // 属性相关状态
  const [attributes, setAttributes] = useState<ProductAttribute[]>([]);
  const [attributeLoading, setAttributeLoading] = useState(false);
  const [attributePagination, setAttributePagination] = useState<PaginationState>({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [attributeModalVisible, setAttributeModalVisible] = useState(false);
  const [editingAttribute, setEditingAttribute] = useState<ProductAttribute | null>(null);
  const [attributeForm] = Form.useForm();

  // 加载商品列表
  const loadProducts = async (params?: ProductListParams) => {
    setProductLoading(true);
    try {
      const response = await productService.getProductList({
        page: productPagination.current,
        pageSize: productPagination.pageSize,
        ...params
      });

      if (response.code === 0 && response.data) {
        setProducts(response.data.list);
        setProductPagination(prev => ({
          ...prev,
          total: response.data!.pagination.total
        }));
      } else {
        message.error(response.message || '获取商品列表失败');
      }
    } catch {
      message.error('获取商品列表失败');
    } finally {
      setProductLoading(false);
    }
  };

  // 加载分类列表
  const loadCategories = async () => {
    setCategoryLoading(true);
    try {
      const response = await productService.getCategoryList({
        page: categoryPagination.current,
        pageSize: categoryPagination.pageSize
      });

      if (response.code === 0 && response.data) {
        setCategories(response.data.list);
        setCategoryPagination(prev => ({
          ...prev,
          total: response.data!.pagination.total
        }));
      } else {
        message.error(response.message || '获取分类列表失败');
      }
    } catch {
      message.error('获取分类列表失败');
    } finally {
      setCategoryLoading(false);
    }
  };

  // 加载属性列表
  const loadAttributes = async () => {
    setAttributeLoading(true);
    try {
      const response = await productService.getAttributeList({
        page: attributePagination.current,
        pageSize: attributePagination.pageSize
      });

      if (response.code === 0 && response.data) {
        setAttributes(response.data.list);
        setAttributePagination(prev => ({
          ...prev,
          total: response.data!.pagination.total
        }));
      } else {
        message.error(response.message || '获取属性列表失败');
      }
    } catch {
      message.error('获取属性列表失败');
    } finally {
      setAttributeLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    if (activeTab === 'products') {
      loadProducts();
    } else if (activeTab === 'categories') {
      loadCategories();
    } else if (activeTab === 'attributes') {
      loadAttributes();
    }
  }, [activeTab, productPagination.current, categoryPagination.current, attributePagination.current]);

  // 商品表格列定义
  const productColumns: ColumnsType<Product> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '商品图片',
      dataIndex: 'image',
      key: 'image',
      width: 100,
      render: (image: string) => {
        if (image) {
          return <Image src={image} width={60} height={60} />
        } else {
          return <div>无图片</div>
        }
      },
    },
    {
      title: '商品名称',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: ProductCategory) => category?.name || '-'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `¥${price.toFixed(2)}`
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock'
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '上架' : '下架'}
        </Tag>
      )
    },
    {
      title: '可购买',
      dataIndex: 'canBuy',
      key: 'canBuy',
      render: (canBuy: boolean) => (
        <Tag color={canBuy ? 'blue' : 'default'}>
          {canBuy ? '是' : '否'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => navigate(`/products/${record.id}`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个商品吗？"
            onConfirm={() => handleDeleteProduct(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 分类表格列定义
  const categoryColumns: ColumnsType<ProductCategory> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditCategory(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个分类吗？"
            onConfirm={() => handleDeleteCategory(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 属性表格列定义
  const attributeColumns: ColumnsType<ProductAttribute> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '属性名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '属性值',
      dataIndex: 'attributeValues',
      key: 'attributeValues',
      render: (values: { value: string }[]) => (
        <Space wrap>
          {values?.map((item, index) => (
            <Tag key={index}>{item.value}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditAttribute(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个属性吗？"
            onConfirm={() => handleDeleteAttribute(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 商品操作处理函数
  const handleAddProduct = () => {
    navigate('/products/new');
  };

  const handleDeleteProduct = async (id: number) => {
    try {
      const response = await productService.deleteProduct(id);
      if (response.code === 0) {
        message.success('删除成功');
        loadProducts();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch {
      message.error('删除失败');
    }
  };

  // 分类操作处理函数
  const handleAddCategory = () => {
    setEditingCategory(null);
    setCategoryModalVisible(true);
    categoryForm.resetFields();
  };

  const handleEditCategory = (category: ProductCategory) => {
    setEditingCategory(category);
    setCategoryModalVisible(true);
    categoryForm.setFieldsValue(category);
  };

  const handleDeleteCategory = async (id: number) => {
    try {
      const response = await productService.deleteCategory(id);
      if (response.code === 0) {
        message.success('删除成功');
        loadCategories();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch {
      message.error('删除失败');
    }
  };

  const handleCategorySubmit = async () => {
    try {
      const values = await categoryForm.validateFields();
      const params: CreateCategoryParams = values;

      let response;
      if (editingCategory) {
        response = await productService.updateCategory(editingCategory.id, params);
      } else {
        response = await productService.createCategory(params);
      }

      if (response.code === 0) {
        message.success(editingCategory ? '更新成功' : '创建成功');
        setCategoryModalVisible(false);
        loadCategories();
      } else {
        message.error(response.message || '操作失败');
      }
    } catch {
      message.error('操作失败');
    }
  };

  // 属性操作处理函数
  const handleAddAttribute = () => {
    setEditingAttribute(null);
    setAttributeModalVisible(true);
    attributeForm.resetFields();
  };

  const handleEditAttribute = (attribute: ProductAttribute) => {
    setEditingAttribute(attribute);
    setAttributeModalVisible(true);
    attributeForm.setFieldsValue({
      ...attribute,
      values: attribute.attributeValues?.map(v => v.value) || []
    });
  };

  const handleDeleteAttribute = async (id: number) => {
    try {
      const response = await productService.deleteAttribute(id);
      if (response.code === 0) {
        message.success('删除成功');
        loadAttributes();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch {
      message.error('删除失败');
    }
  };

  const handleAttributeSubmit = async () => {
    try {
      const values = await attributeForm.validateFields();
      
      let attributeValues: Array<{ id?: number; value: string }> = [];
      
      if (editingAttribute) {
        // 编辑时需要智能处理：保留原有值的ID，新增值不分配ID
        attributeValues = values.values?.map((value: string) => {
          // 查找是否在原有的attributeValues中存在相同的值
          const existingItem = editingAttribute.attributeValues?.find(item => item.value === value);
          if (existingItem) {
            // 保留原有ID
            return { id: existingItem.id, value };
          } else {
            // 新增的值，不分配ID
            return { value };
          }
        }) || [];
      } else {
        // 新建时，所有值都没有ID
        attributeValues = values.values?.map((value: string) => ({ value })) || [];
      }

      const params: CreateAttributeParams = {
        ...values,
        status: 1,
        type: 'singleSelect', // 根据你的数据示例，使用singleSelect
        attributeValues,
        values: attributeValues // 保持兼容性，同时传递两个字段
      };

      let response;
      if (editingAttribute) {
        response = await productService.updateAttribute(editingAttribute.id, params);
      } else {
        response = await productService.createAttribute(params);
      }

      if (response.code === 0) {
        message.success(editingAttribute ? '更新成功' : '创建成功');
        setAttributeModalVisible(false);
        loadAttributes();
      } else {
        message.error(response.message || '操作失败');
      }
    } catch {
      message.error('操作失败');
    }
  };

  return (
    <Layout className="products-layout">
      {/* 统一页头 */}
      <div className="products-header">
        <div className="header-left">
          <Button 
            className="back-button" 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            size="large" 
            onClick={handleBack} 
          />
          <h1 className="page-title">商品管理</h1>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="products-content">
        <Card>
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab="商品管理" key="products">
              <div style={{ marginBottom: 16 }}>
                <Row justify="space-between" align="middle">
                  <Col>
                    <Title level={4}></Title>
                  </Col>
                  <Col>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddProduct}
                    >
                      添加商品
                    </Button>
                  </Col>
                </Row>
              </div>

              <Table
                columns={productColumns}
                dataSource={products}
                rowKey="id"
                loading={productLoading}
                pagination={{
                  current: productPagination.current,
                  pageSize: productPagination.pageSize,
                  total: productPagination.total,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                  onChange: (page, pageSize) => {
                    setProductPagination(prev => ({
                      ...prev,
                      current: page,
                      pageSize: pageSize || 10
                    }));
                  }
                }}
              />
            </TabPane>

            <TabPane tab="分类管理" key="categories">
              <div style={{ marginBottom: 16 }}>
                <Row justify="space-between" align="middle">
                  <Col>
                    <Title level={4}></Title>
                  </Col>
                  <Col>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddCategory}
                    >
                      添加分类
                    </Button>
                  </Col>
                </Row>
              </div>

              <Table
                columns={categoryColumns}
                dataSource={categories}
                rowKey="id"
                loading={categoryLoading}
                pagination={{
                  current: categoryPagination.current,
                  pageSize: categoryPagination.pageSize,
                  total: categoryPagination.total,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                  onChange: (page, pageSize) => {
                    setCategoryPagination(prev => ({
                      ...prev,
                      current: page,
                      pageSize: pageSize || 10
                    }));
                  }
                }}
              />
            </TabPane>

            <TabPane tab="属性管理" key="attributes">
              <div style={{ marginBottom: 16 }}>
                <Row justify="space-between" align="middle">
                  <Col>
                    <Title level={4}></Title>
                  </Col>
                  <Col>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddAttribute}
                    >
                      添加属性
                    </Button>
                  </Col>
                </Row>
              </div>

              <Table
                columns={attributeColumns}
                dataSource={attributes}
                rowKey="id"
                loading={attributeLoading}
                pagination={{
                  current: attributePagination.current,
                  pageSize: attributePagination.pageSize,
                  total: attributePagination.total,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                  onChange: (page, pageSize) => {
                    setAttributePagination(prev => ({
                      ...prev,
                      current: page,
                      pageSize: pageSize || 10
                    }));
                  }
                }}
              />
            </TabPane>
          </Tabs>
        </Card>
      </div>

      {/* 分类编辑模态框 */}
      <Modal
        title={editingCategory ? '编辑分类' : '添加分类'}
        open={categoryModalVisible}
        onOk={handleCategorySubmit}
        onCancel={() => setCategoryModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={categoryForm}
          layout="vertical"
          initialValues={{
            status: 1,
            sort: 0
          }}
        >
          <Form.Item
            label="分类名称"
            name="name"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入排序值"
            />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            valuePropName="checked"
            getValueFromEvent={(checked) => checked ? 1 : 0}
            getValueProps={(value) => ({ checked: value === 1 })}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 属性编辑模态框 */}
      <Modal
        title={editingAttribute ? '编辑属性' : '添加属性'}
        open={attributeModalVisible}
        onOk={handleAttributeSubmit}
        onCancel={() => setAttributeModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={attributeForm}
          layout="vertical"
          initialValues={{
            status: 1,
            type: 'text'
          }}
        >
          <Form.Item
            label="属性名称"
            name="name"
            rules={[{ required: true, message: '请输入属性名称' }]}
          >
            <Input placeholder="请输入属性名称" />
          </Form.Item>

          <Form.Item
            label="属性值"
            name="values"
            rules={[{ required: true, message: '请输入属性值' }]}
          >
            <Select
              mode="tags"
              style={{ width: '100%' }}
              placeholder="请输入属性值，按回车添加"
              tokenSeparators={[',']}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default ProductsPage; 